package ResImpl;

import java.io.Serializable;
import java.util.LinkedList;


public class TransactionManager implements Serializable{
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private int nextTransactionId = 1;
	private LinkedList<Transaction> transactions;
	
	
	public TransactionManager(){
		transactions = new LinkedList<Transaction>();
	}
	
	public int startNewTransaction(){
		int id = nextTransactionId;
		transactions.add(new Transaction(id));
		nextTransactionId++;
		return id;
	}

	public void startNewTransaction(int id){
		transactions.add(new Transaction(id));
		nextTransactionId++;
	}
	
	public void commit(int id){
		for(int i=0;i<transactions.size();i++){
			if(transactions.get(i).getId()==id){
				transactions.get(i).commit();
			}
		}
	}
	
	public void abort(int id){
		for(int i=0;i<transactions.size();i++){
			if(transactions.get(i).getId()==id){
				transactions.get(i).abort();
			}
		}
	}
	
	public boolean isIdValid(int xId){
		boolean exists = false;
		boolean committed = false;
		boolean aborted = false;
		
		for(int i = 0; i< transactions.size();i++){
			Transaction t = transactions.get(i);
			if(t.getId()==xId){
				exists = true;
				committed = t.isCommited();
				aborted = t.isAborted();
			}
		}
		
		return (exists && (!committed) && (!aborted));
	}
	
	public Transaction getTransactionById(int id){
		for(int i = 0;i<transactions.size();i++){
			Transaction t = transactions.get(i);
			if(t.getId()==id){
				return t;
			}
		}
		return null;
	}
	
	public LinkedList<Transaction> getExpiredTransactions(){
		
		LinkedList<Transaction> expiredList = new LinkedList<Transaction>();
		for(int i = 0;i<transactions.size();i++){
			Transaction t = transactions.get(i);
			if(t.getElapsedTime()>45&&(!t.isAborted())&&(!t.isCommited())){
				expiredList.add(t);
			}
		}
		return expiredList;
	}
	
	public void resetTTL(int xId){
		for(int i = 0;i<transactions.size();i++){
			Transaction t = transactions.get(i);
			if(t.getId()==xId){
				t.resetTTL();
			}
		}
	}

	public LinkedList<Transaction> getUnresolved(){

		LinkedList<Transaction> unresolvedList = new LinkedList<Transaction>();
		for(int i = 0;i<transactions.size();i++){
			Transaction t = transactions.get(i);
			if(!t.isAborted()&&!t.isCommited()){
				unresolvedList.add(t);
			}
		}
		return unresolvedList;
	}

	

}
